<script lang="ts" setup>
import ShowResources from '@/component/Upload/ShowResources.vue'
import { useBackgroundSettingStore } from '@/config/store/UseBackgroundSettingStore.ts'
import { useVisibilityChangeListener } from '@/tool/UseEventListener.ts'
import { storeToRefs } from 'pinia'
import { computed, type CSSProperties, onMounted, type Ref, ref, watch } from 'vue'

const { currentSetting } = storeToRefs(useBackgroundSettingStore())
const videoRef: Ref<HTMLVideoElement | null, HTMLVideoElement> = ref(null)

const rate = computed(() => currentSetting.value.video!.rate)
const setRate = () => {
    if (!videoRef.value) {
        return
    }
    console.debug('播放速度', rate.value)
    videoRef.value.playbackRate = rate.value
}
onMounted(setRate)
watch(() => rate, setRate)

useVisibilityChangeListener(
        () => {
            console.debug('开始播放', videoRef.value?.currentTime)
            videoRef.value?.play()
        },
        () => {
            console.debug('暂停播放', videoRef.value?.currentTime)
            videoRef.value?.pause()
        },
)

const customStyle = computed<CSSProperties>(() => {
    const { topCrop = 0, rightCrop = 0, bottomCrop = 0, leftCrop = 0 } = currentSetting.value!.video ?? {}
    return {
        width: `calc(100vw + ${ leftCrop + rightCrop }px)`,
        height: `calc(100vh + ${ topCrop + bottomCrop }px)`,
        top: `-${ topCrop }px`,
        right: `-${ rightCrop }px`,
        bottom: `-${ bottomCrop }px`,
        left: `-${ leftCrop }px`,
    }
})


</script>

<template>
<ShowResources :uri="currentSetting.video!.uri">
    <template #default="{url, isLoading}">
        <video
                v-if="!isLoading"
                ref="videoRef"
                :controls="false"
                :src="url"
                :style="customStyle"
                autoplay
                class="background-video"
                loop
                muted
                playsinline
                preload="metadata"
        />
    </template>
</ShowResources>
</template>

<style scoped>
.background-video {
    object-fit: cover;
    object-position: center;
}
</style>
